package com.google.code.swingonfire.component.foldable;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.SwingConstants;

import com.google.code.swingonfire.plotter.ArrowSketch;
import com.google.code.swingonfire.plotter.Plotter;

public class DefaultJFoldableIndicator extends AbstractJFoldableIndicator implements MouseListener
{

    private static final long serialVersionUID = -6093014192450303066L;

    private final Plotter plotter = new Plotter(new ArrowSketch(0.5, 0.25, 0.5));

    private double rotatedWhenClosed = 0;
    private double rotatedWhenOpened = Math.PI;

    public DefaultJFoldableIndicator()
    {
        super();

        setMinimumSize(new Dimension(24, 24));
        setPreferredSize(new Dimension(24, 24));
        setOpaque(false);

        addMouseListener(this);
    }

    @Override
    public void setDirection(int direction)
    {
        super.setDirection(direction);

        switch (direction)
        {
            case SwingConstants.NORTH:
                rotatedWhenClosed = 0;
                rotatedWhenOpened = Math.PI / 2;
                break;

            case SwingConstants.SOUTH:
                rotatedWhenClosed = 0;
                rotatedWhenOpened = -Math.PI / 2;
                break;

            case SwingConstants.EAST:
                rotatedWhenClosed = Math.PI / 2;
                rotatedWhenOpened = Math.PI;
                break;

            case SwingConstants.WEST:
                rotatedWhenClosed = Math.PI / 2;
                rotatedWhenOpened = 0;
                break;

            default:
                break;
        }
    }

    @Override
    public void paint(Graphics g)
    {
        super.paint(g);

        Graphics2D g2d = (Graphics2D) g.create();

        g2d.translate(getWidth() / 2, getHeight() / 2);

        plotter.size(new Dimension(10, 10));
        plotter.draw(g2d);
    }

    @Override
    public void foldingInProgress(FoldableEvent event)
    {
        double rotation =
            rotatedWhenClosed + ((rotatedWhenOpened - rotatedWhenClosed) * event.getInterpolatedFraction());

        plotter.rotate(rotation);
        repaint();
    }

    @Override
    public void mouseClicked(MouseEvent e)
    {
        // intentionally left blank
    }

    @Override
    public void mousePressed(MouseEvent e)
    {
        // intentionally left blank
    }

    @Override
    public void mouseReleased(MouseEvent e)
    {
        fireActionPerformed();
        e.consume();
    }

    @Override
    public void mouseEntered(MouseEvent e)
    {
        // intentionally left blank
    }

    @Override
    public void mouseExited(MouseEvent e)
    {
        // intentionally left blank
    }

}
